package com.yootoo.extpmml.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yootoo.extpmml.Entites.model.ModelDesc;
import com.yootoo.extpmml.Exception.ModelExecuteException;
import com.yootoo.extpmml.constant.Constants;
import com.yootoo.extpmml.service.BaseOperateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping(value = Constants.SERVICE_NAME + "/" + Constants.VERSION,produces = "application/json")
@Api("模型调用并执行接口")
public class ModelExcuteController {
    private static final Logger logger = LoggerFactory.getLogger(ModelExcuteController.class);
    @Autowired
    private BaseOperateService<ModelDesc> modelOperateService;



    @ApiOperation("模型统一执行")
    @ApiImplicitParam(name = "records", value = "模型执行输入json,包含model_name、model_vars", paramType = "body", required = true)
    @RequestMapping(value = "/predict", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public Map<String, Object> modelExec(@RequestBody JSONObject records){
        String name = records.getString(Constants.EVALUATOR_KEY);
        JSONObject record = records.getJSONObject(Constants.EVALUATOR_MODEL_VARS);

        long start = System.currentTimeMillis();
        Map<String, Object> res = Maps.newHashMap();
        Map<String, Object> executeRes = null;
        try {
            executeRes = modelOperateService.execute(name, JSON.toJSONString(record));
            res.put("status","success");
        } catch (Exception e) {
//            throw new ModelExecuteException("模型执行异常",e);
            logger.error("模型执行异常",e);
            res.put("errorReason",e.getMessage());
            res.put("status","failed");

        }
        res.put("result",executeRes);
        long end = System.currentTimeMillis();
        logger.info("exec model :{} success. {}ms",name,end - start);
        return res;
    }

    @ApiOperation("模型上线")
    @ApiImplicitParam(name = "name", value = "模型名字", required = true)
    @RequestMapping(value = "/up", method = RequestMethod.GET)
    public ModelDesc up(@RequestParam String name){
        return modelOperateService.up(name);
    }

    @ApiOperation("模型下线")
    @ApiImplicitParam(name = "name", value = "模型名字", required = true)
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    public ModelDesc down(@RequestParam String name){
        return modelOperateService.down(name);
    }

}
